﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Word = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Runtime.InteropServices;
using System.IO;

public partial class Aplicacion_Vista_IngresarMaterial : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        String nomRol = (String)Session["nombreRol"];
        String nomU = (String)Session["nombreUsuario"];

        if (nomRol == null || nomRol.Length <= 0 || nomU == null || nomU.Length <= 0)
        {
            Response.Redirect("Inicio.aspx");
        }
        
        Session["idProy"] = Request.QueryString["i"];
        ControladorIngresarMaterial control = new ControladorIngresarMaterial();
        DataTable dt = control.cargaInicial(Label1.Visible, (String)Session["idProy"], GridView1, Button2, TextBox2);
        Label1.Visible = false;
        if (dt != null)
        {
            Session["estimacionMat"] = dt;
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }




    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Session["nombreRol"] = null;
        Session["nombreUsuario"] = null;
        Session["idRol"] = null;
        Session.Abandon();
        Response.Redirect("Inicio.aspx", true);
    }


    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        String sItem = DropDownList1.SelectedValue;
        for (int i = 0; i < DropDownList2.Items.Count; i++)
        {
            if (DropDownList2.Items[i].Value == sItem)
            {
                DropDownList2.SelectedIndex = i;
            }
        }
        
        for (int j = 0; j < DropDownList4.Items.Count; j++)
        {
            if (DropDownList4.Items[j].Value == sItem)
            {
                DropDownList4.SelectedIndex = j;
            }
        }

    }

    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        String sItem = DropDownList2.SelectedValue;
        for (int i = 0; i < DropDownList1.Items.Count; i++)
        {
            if (DropDownList1.Items[i].Value == sItem)
            {
                DropDownList1.SelectedIndex = i;
            }
        }
        for (int j = 0; j < DropDownList4.Items.Count; j++)
        {
            if (DropDownList4.Items[j].Value == sItem)
            {
                DropDownList4.SelectedIndex = j;
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        String idMaterial = DropDownList1.SelectedValue;
        String nomMaterial = DropDownList1.SelectedItem.Text;
        String skuMaterial = DropDownList2.SelectedItem.Text;
        String cantidadMaterial = DropDownList3.SelectedItem.Text;
        DataTable dt = (DataTable)Session["estimacionMat"];
        for (int i = 0; i < dt.Rows.Count; i++)
        { 
            String idMat = dt.Rows[i].ItemArray[0].ToString();
            if (idMat == idMaterial)
            {
                cantidadMaterial = (Int32.Parse(cantidadMaterial) + Int32.Parse(dt.Rows[i].ItemArray[3].ToString())).ToString();
                dt.Rows.RemoveAt(i);
            }
        }
        
        DataRow r = dt.NewRow();
        r["idMaterial"] = idMaterial;
        r["nombreMaterial"] = nomMaterial;
        r["skuMaterial"] = skuMaterial;
        r["cantidadMaterial"] = cantidadMaterial;
        dt.Rows.Add(r);
        Session["estimacionMat"] = dt;
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        DataTable dt = (DataTable)Session["estimacionMat"];
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        DataTable dt = (DataTable)Session["estimacionMat"];
        
        if (e.CommandName == "quitar material")
        {
            
            int page = GridView1.PageIndex;
            int numPages = GridView1.PageSize;
            int preindex = Int16.Parse(e.CommandArgument.ToString());
            int index = preindex + page * numPages;
            dt.Rows.RemoveAt(index);

        }


        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        DataTable dt = (DataTable)Session["estimacionMat"];
        String idProyecto = (String)Session["idProy"];
        String fila = "";
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            String idMat = dt.Rows[i].ItemArray[0].ToString();
            String cantEstimada = dt.Rows[i].ItemArray[3].ToString();
            fila = fila + idMat + "," + idProyecto + "," + cantEstimada + ";";
        }

        String numFilas = dt.Rows.Count.ToString();
        ControladorIngresarMaterial control = new ControladorIngresarMaterial();
        control.insertEstimacionMaterial(idProyecto, fila, numFilas,Button2,TextBox2);
        Button3.Visible = true;
    }
    protected void Button3_Click(object sender, EventArgs e)
    {

        String hola = "";
        ControladorIngresarMaterial controla = new ControladorIngresarMaterial();
        try
        {


            object oMissing = System.Reflection.Missing.Value;
            hola = "1";
            //Start Word and create a new document.
            Word._Application oWord = null;
            Word._Document oDoc = null;
            hola += "2";
            oWord = new Word.Application();
            //oWord.Visible = true;
            ControladorGenerarDocumentos control = new ControladorGenerarDocumentos();
            //ModeloInfoProyecto info = new ModeloInfoProyecto();
            DateTime dat = DateTime.Now;
            hola += "3";
            object oTemplate = "C:\\peticionMaterial.dot";
            oDoc = oWord.Documents.Add(oTemplate, oMissing , oMissing , oMissing);
            String result = control.RetornarNombre((String)Session["nombreUsuario"]);
            String resultadoDatosProyecto = control.retornarDatosProyecto((String)Session["idProy"]);
            DataTable dt = control.materialesEstimados((String)Session["idProy"]);
            hola += "4";
            String[] res = result.Split('#');
            //hola += "::4.1.1::";
            String[] datosProy = resultadoDatosProyecto.Split('#');
            //hola += "::4.1.2::";
            hola += "4.1-";
            object oBookMark = "nombre_usuario";
            

            oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = res[0].ToUpper();
            hola += "4.2-";
            object oBookMark1 = "cargo_usuario";
            oDoc.Bookmarks.get_Item(ref oBookMark1).Range.Text = res[1].ToUpper();
            hola += "4.3-";
            object fecha_larga = "fecha_larga";
            oDoc.Bookmarks.get_Item(fecha_larga).Range.Text = dat.Day.ToString() + " de " + DateTime.Now.ToString("MMMM") + " del " + dat.Year.ToString();
            object departamento = "departamento_proyecto";
            hola += "4.4-";
            String depto = datosProy[1];
            hola += "4.5-";
            String[] datosDepto = depto.Split(' ');
            oDoc.Bookmarks.get_Item(ref departamento).Range.Text = datosDepto[1].ToUpper();
            hola += "4.6-";
            object nombre = "nombre_proyecto";
            oDoc.Bookmarks.get_Item(ref nombre).Range.Text = datosProy[0];
            hola += "5"; 

            Word.Table oTable;
            object estimacion = "estimacion_materiales";
            Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref estimacion).Range;
            int filas = dt.Rows.Count;
            oTable = oDoc.Tables.Add(wrdRng, filas , 1 , ref oMissing, ref oMissing);
            oTable.Range.ParagraphFormat.SpaceAfter = 2;
            hola += "6";
            string strText;

            int i;
            for (i = 1; i <= filas ; i++)
            {
                String cant = dt.Rows[i-1].ItemArray[0].ToString();
                String nom = dt.Rows[i-1].ItemArray[1].ToString();
                String unid = dt.Rows[i - 1].ItemArray[2].ToString();
                strText = cant + " " + unid + " " + nom;
                oTable.Cell(i, 1).Range.Text = strText;
            }
      
            oDoc.SaveAs("C:\\EstimacionMaterial.doc");
            oWord.Quit();



            //filepath = \\server\folder\en_vs_2005_pro_dvd.iso

            String filePath = "C:\\EstimacionMaterial.doc";

            //somehow, you need to know what file name is: e.g.  en_vs_2005_pro_dvd.iso
            String[] fileName = filePath.Split(new char[] { '\\' });

            FileStream fs = null;
            //Either use the current logged in user's credentials or use some different user.

            //-----------------------------
            //To use the current logged in user's credentials, you can call directly the following
            //fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            //-----------------------------

            //-----------------------------
            //To use the some other Network user's credentials, use the following:

            //Add the required namespaces: 
            //using System.Security.Principal;
            IntPtr token = IntPtr.Zero;
            
            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            
            //-----------------------------

            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            //To forcefully download, even for Excel, PDF files, regardless of your IE's settings which may allow to open the files right in the browser.
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName[fileName.Length - 1].ToString());

            long bytesToGo;
            int bytesRead;
            Byte[] buffer = new byte[1048576];    //1 MB buffer, you may want to use whatever fits your environment

            bytesToGo = fs.Length;

            while (bytesToGo > 0)
            {
                if (Response.IsClientConnected)
                {
                    bytesRead = fs.Read(buffer, 0, 1048576);
                    Response.OutputStream.Write(buffer, 0, bytesRead);
                    Response.Flush();
                    bytesToGo -= bytesRead;
                }
                else
                {
                    bytesToGo = -1;
                }
            }

            fs.Close();
           
            controla.set(1, "El archivo fué creado satisfactoriamente");
            Response.Flush();              


            }

            
        
        catch (Exception exc)
        {
            controla.set(-1, "Ocurrió un error al intentar generar el archivo");
        }
    }
}